#include "GameStateManager.hpp"
#include <OGRE/OgreLogManager.h>
void GameStateManager::AddState(GameState* state)
{
	state->SetManager(this);
	m_GameState.push_back(state);
}

void GameStateManager::ChangeState(int state)
{
	//m_GameState[state]->Resume();
	//pause state currently on top of the active stack
	if (m_ActiveGameState.size() > 0)
		m_ActiveGameState.front()->Pause();
	//initialize the state if this hasn't been done yet
	if (!m_GameState[state]->IsInitialized())
	{
		m_GameState[state]->Init();
	}
	m_ActiveState = state;
	//place the specified gamestate in the front of the stack
	//if it already exists, we move to the front instead
	if (m_GameState[state]->IsActive())
	{
		std::list<GameState*>::iterator iter = m_ActiveGameState.begin();
		while (iter != m_ActiveGameState.end())
		{
			if ((*iter) == m_GameState[state])
			{
				m_ActiveGameState.push_front(m_GameState[state]);
				m_ActiveGameState.erase(iter);
				iter = m_ActiveGameState.end();
				continue;
				//m_ActiveGameState.splice(iter, m_ActiveGameState, m_ActiveGameState.begin());
			}
			iter++;
		}
	} else
	{
		Ogre::LogManager::getSingletonPtr()->logMessage("Adding gamestate to active list...");
		m_GameState[state]->SetActive(true);
		m_ActiveGameState.push_front(m_GameState[state]);
	}
	m_ActiveGameState.front()->Resume();
}


void GameStateManager::RunActiveStates(double delta)
{
	/*
		the pointers are stored in a temp vector to avoid
		the problem of the items in the list possibly
		rearranging themselves during the actual loop
	*/
	std::list<GameState*>::iterator iter = m_ActiveGameState.begin();
	std::vector<GameState*> vecPtr;

	while (iter != m_ActiveGameState.end())
	{
		vecPtr.push_back(*iter);
		iter++;
	}

	for (int i = 0; i < vecPtr.size(); i++)
		vecPtr[i]->Run(delta);
}
